package ThreadCommunication;

public class ProducerConsumer
{
    public static void main(String[] args)
    {
        SynContainer synContainer = new SynContainer();
        new Productor(synContainer).start();
        new Consumer(synContainer).start();
    }
}

class Productor extends Thread
{
    SynContainer container;
    public Productor(SynContainer container)
    {
        this.container = container;
    }
    public void run()
    {
        for (int i = 0; i < 100; i++)
        {
            System.out.println("Produce No." + i + "Chicken");
            try
            {
                container.push(new Chicken(i));
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
}

class Consumer extends Thread
{
    SynContainer container;
    public Consumer(SynContainer container)
    {
        this.container = container;
    }
    public void run()
    {
        for (int i = 0; i < 100; i++)
        {
            System.out.println("Consume No." + i + "Chicken");
            try
            {
                container.pop();
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
}

class Chicken
{
    int No;

    public Chicken(int No)
    {
        this.No = No;
    }
}

class SynContainer
{
    Chicken[] chickens = new Chicken[10];
    int count = 0;
    //放入产品
    public synchronized void push(Chicken chicken) throws InterruptedException
    {
        //容器满了，等待消费
        if (count == chickens.length)
        {
            this.wait();
        }
        //如果没有满，则丢入产品
        chickens[count] = chicken;
        count++;
        this.notifyAll();
    }
    //取出产品
    public synchronized Chicken pop() throws InterruptedException
    {
        //容器空了，等待生产
        if (count == 0)
        {//等待生产
            this.wait();
        }
        //如果不是空的，消费
        count--;
        Chicken chicken = chickens[count];
        this.notifyAll();
        return chicken;
    }
}
